from http.server import HTTPServer, SimpleHTTPRequestHandler
import sys
import os

class CORSRequestHandler(SimpleHTTPRequestHandler):
    def end_headers(self):
        self.send_header('Access-Control-Allow-Origin', '*')
        self.send_header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS')
        self.send_header('Access-Control-Allow-Headers', 'X-Requested-With')
        self.send_header('Access-Control-Allow-Headers', 'Content-Type')
        super().end_headers()

    def do_GET(self):
        # 确保 config 目录存在
        if self.path.endswith('/config/sites.json'):
            config_path = os.path.join(os.getcwd(), 'config/sites.json')
            if not os.path.exists(config_path):
                self.send_response(404)
                self.end_headers()
                self.wfile.write(b'{"error": "Configuration file not found"}')
                return
        return super().do_GET()

def run_server(port=8000):
    try:
        # 切换到脚本所在目录
        os.chdir(os.path.dirname(os.path.abspath(__file__)))
        # 解决上线时，无法访问本地文件的问题
        server_address = ('0.0.0.0', port)
        httpd = HTTPServer(server_address, CORSRequestHandler)
        print(f"启动本地服务器在 http://localhost:{port}")
        print(f"当前工作目录: {os.getcwd()}")
        print("按 Ctrl+C 停止服务器")
        httpd.serve_forever()
    except OSError as e:
        if e.errno == 98 or e.errno == 10048:  # 端口被占用 (Linux/Windows)
            print(f"端口 {port} 已被占用，尝试其他端口...")
            run_server(port + 1)
        else:
            raise e
    except KeyboardInterrupt:
        print("\n关闭服务器")
        httpd.server_close()
        sys.exit(0)

if __name__ == '__main__':
    run_server() 